//
//  NotificationManager.m
//  VehicleNetStore
//
//  Created by xxcao on 2017/6/26.
//  Copyright © 2017年 MobileArtisan. All rights reserved.
//

#import "NotificationManager.h"
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "GeTuiSdk.h" // GetuiSdk头 件应
// iOS10 及以上需导  UserNotifications.framework
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif

NSString *kGtAppId = @"6jEnp1mu6c8PiXHvHvPGo";
NSString *kGtAppKey = @"QfBw37SUrP8U31CaxCAj7A";
NSString *kGtAppSecret = @"bcaU97PpDq59NoppDNxgB8";
NSString *kGtMasterSecret = @"h8WwjtgSTy6HaeIonCfdM5";

@interface NotificationManager ()<GeTuiSdkDelegate, UNUserNotificationCenterDelegate, UIAlertViewDelegate>

@property(nonatomic, assign)NSTimeInterval timeInterval;

@end

@implementation NotificationManager

static NotificationManager *singleton = nil;

+ (id)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!singleton) {
            singleton = [[[self class] alloc] init];
            singleton.timeInterval = 0;
        }
    });
    return singleton;
}

- (BOOL)startPush {
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注:该 法需要在主线程中调
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    //[1-2]:设置是否后台运行开关
    [GeTuiSdk runBackgroundEnable:NO];
    //[1-3]:设置电子围栏功能，开启LBS定位服务 和 是否允许SDK 弹出用户定位请求
    [GeTuiSdk lbsLocationEnable:YES andUserVerify:YES];
    
    // 注册 APNs
    [self registerRemoteNotification];
    return YES;
}

+ (BOOL)isMessageNotificationServiceOpen {
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        return UIRemoteNotificationTypeNone != [[UIApplication sharedApplication] currentUserNotificationSettings].types;
    } else {
        return UIRemoteNotificationTypeNone != [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
    }
}

#pragma mark - 用户通知(推送) _自定义方法

/** 注册远程通知 */
- (void)registerRemoteNotification {
    /*
     警告：Xcode8的需要手动开启“TARGETS -> Capabilities -> Push Notifications”
     */
    
    /*
     警告：该方法需要开发者自定义，以下代码根据APP支持的iOS系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的iOS系统都能获取到DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (granted) {
                NSLog(@"允许接收推送");
                UserDefaultsSave(@"onpush", @"status");
                UserDefaultsSave(@"Yes", @"isFirst");
            } else {
                UserDefaultsSave(@"offpush", @"status");
                UserDefaultsSave(@"No", @"isFirst");
            }
            
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
    }
    else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else {
        //        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
        //                                                                       UIRemoteNotificationTypeSound |
        //                                                                       UIRemoteNotificationTypeBadge);
        //        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}

- (void)registerDeviceToken:(NSString *)deviceToken {
    if (deviceToken && deviceToken.length > 0 && ![deviceToken isEqualToString:@""]) {
        [GeTuiSdk registerDeviceToken:deviceToken];
    }
}

- (void)handleAMessage:(id)msg Type:(EPushResponseType)pushResponseType {
    //用户不允许推送消息
    if ([UserDefaultsGet(@"status") isEqualToString:@"offpush"]) {
        return;
    }
    //to do here
    //解析推送通知，跳转相应页面
    NSString *otherBtn = @"确定";
    NSString *message = @"您有一条新消息，确定要查看？";
    self.url = @"";
    
    NSDictionary *dict = nil;
    if (pushResponseType == EPushResponseGeTui) {
        dict = [NSJSONSerialization JSONObjectWithData:msg options:kNilOptions error:nil];
    } else {
        dict = [NSDictionary dictionaryWithDictionary:msg];
        if ([dict.allKeys containsObject:@"payload"]) {
            dict = [NSDictionary dictionaryWithDictionary:dict[@"payload"]];
        }
    }
    NSLog(@"dict:%@", dict);
    if ([dict.allKeys containsObject:@"msgType"]) {
        self.msgType = [dict[@"msgType"] integerValue];
        switch ([dict[@"msgType"] integerValue]) {
            case MsgTypeIntegralAdd:
            {
                message = @"e车城通知您:您的积分增加啦! ";
                otherBtn = @"确定";
            }
                break;
                
            case MsgTypeIntegralChange:
            {
                message = @"e车城通知您:您的积分有变化! ";
                otherBtn = @"确定";
            }
                break;
            case MsgTypeOrderGenerated:
            {
                message = @"e车城通知您:您有新订单生成! ";
                otherBtn = @"查看";
                self.url = dict[@"msgAlert"];
            }
                break;
            case MsgTypeNewOrderGenerated:
            {
                message = @"e车城通知您:您有新的活动订单生成啦! ";
                otherBtn = @"确定";
            }
                break;
            case MsgTypePromotionActivities:
            {
                message = @"e车城通知您:商城有新的特卖活动啦 ";
                otherBtn = @"确定";
            }
                break;
            case MsgTypeNews:
            {
                message = @"e车城通知您:您有一条新资讯 ";
                otherBtn = @"查看";
                self.url = dict[@"msgAlert"];
            }
                break;
            default:
                break;
        }
    };
    
    NSTimeInterval now = [NSDate date].timeIntervalSince1970;
    if (self.msgType != MsgTypeNews && self.msgType != MsgTypeOrderGenerated) {
        NSLog(@"弹出的alert消息");
        if (now - self.timeInterval > 0.5) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"忽略" otherButtonTitles:nil, nil];
            [alert show];
        }
        self.timeInterval = now;
    } else {
        if (now - self.timeInterval > 0.5) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"查看", nil];
            [alert show];
        }
        self.timeInterval = now;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_Key_News" object:self.url];
    }
}

#pragma mark - iOS 10中收到推送消息

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
#warning 点击通知进入app iOS10以上
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    //to do 解析消息进入app iOS10以上
    [[NotificationManager sharedInstance] handleAMessage:response.notification.request.content.userInfo Type:EPushResponseIOS10Up];
    completionHandler();
}
#endif

#pragma mark - GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    NSLog(@"\n>>[GTSdk RegisterClient]:%@\n\n", clientId);
#warning to do here
    AppDelegate *appdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appdelegate.clientId = clientId;
    if (clientId.length > 0 && appdelegate.userId.length > 0) {
        [appdelegate uploadClient_Id];
    }
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>[GTSdk error]:%@\n\n", [error localizedDescription]);
}


/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    // [ GTSdk ]：汇报个推自定义事件(反馈透传消息)
    //    [GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];
    
    // 数据转换
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    
    // 控制台打印日志
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@", taskId, msgId, payloadMsg, offLine ? @"<离线消息>" : @""];
    NSLog(@"\n>>[GTSdk ReceivePayload]:%@\n\n", msg);
#warning to do here...
    if(!offLine) {
        //如果在线，直接解析通知，跳转咨询列表页面
        [[NotificationManager sharedInstance] handleAMessage:payloadData Type:EPushResponseGeTui];
    }
}

/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // 发送上行消息结果反馈
    NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
    NSLog(@"\n>>[GTSdk DidSendMessage]:%@\n\n", msg);
}

/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // 通知SDK运行状态
    NSLog(@"\n>>[GTSdk SdkState]:%u\n\n", aStatus);
}

/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        NSLog(@"\n>>[GTSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
        return;
    }
    NSLog(@"\n>>[GTSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
}

@end
